package com.sky.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.sky.constant.MessageConstant;
import com.sky.exception.ServiceException;
import com.sky.service.OssService;
import com.sky.utils.AliOssUtil;
import com.sky.utils.DateUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;

/**
 * @program: guli_parent
 * @description: 对象存储服务层实现类
 * @author: zl
 * @create: 2022-05-12 15:29
 **/
@Slf4j
@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Override
    public String upload(MultipartFile file,String name) {

        try {
            //获取file名称
            String fileName = file.getOriginalFilename();

            //生成随机性唯一值，使用uuid，添加到名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            if (fileName != null && fileName.length() < 20) {
                fileName = uuid + fileName;
            }

            //按照当前日期，创建文件夹，上传到创建的文件夹里
            String timeUrl = DateUtils.datePath();

            fileName = name+"/"+timeUrl+"/"+fileName;

            return aliOssUtil.upload(file.getBytes(), fileName);
        }catch (Exception e){
            throw new ServiceException(MessageConstant.UPLOAD_FAILED);
        }
    }
}
